package com.kapcb.assemble.chain;

import java.util.function.BiConsumer;

/**
 * <a>Title: HandlerExecutionChain </a>
 * <a>Author: cb <a>
 * <a>Description: HandlerExecutionChain <a>
 *
 * @author cb
 * @version 1.0
 * @date 2024/4/18 5:37 PM
 * @since 1.0
 */
public class HandlerExecutionChain<T extends ChainRequest, R extends ChainResponse> implements Chain<T, R> {

    /**
     * 责任链数组
     */
    private Chain<T, R>[] chains;

    /**
     * 当前执行责任链的位置
     */
    private int position = 0;

    /**
     * 责任链中节点的数量
     */
    private int cnt = 0;

    /**
     * 目标方法
     */
    private BiConsumer<T, R> targetMethod;

    private HandlerExecutionChain() {
    }

    public static <T extends ChainRequest, R extends ChainResponse> HandlerExecutionChain newHandlerExecutionChain() {
        HandlerExecutionChain handlerExecutionChain = new HandlerExecutionChain();
        return new HandlerExecutionChain();
    }

    @Override
    public void handle(T request, R response) {
        if (this.cnt <= 0 || this.position >= this.cnt) {
            if (this.targetMethod != null) {
                targetMethod.accept(request, response);
            }
            return;
        }
        Chain<T, R> currentChain = this.chains[this.position++];
        currentChain.handle(request, response);
    }

}
